#include	"../network/LoginService.h"
#include	"../network/CenterConnector.h"
#include	"../utils/Http.h"

#include	<protocols/Common.pb.h>
#include	<Json.h>

void VerifySina(Sender * sender, const std::string & token, uint32_t sid, const std::string & code, uint32_t serial) {
	std::string url = "https://api.weibo.com/oauth2/get_token_info";
	std::string param = "access_token=" + token;
	uint64_t client = sender->Id();
	Http * request = new Http();
	
	request->SetErrorHandler([=]() {
		Sender * from = LoginService::Instance().Find(client);
		LoginService::Instance().FailedVerify(from, Proto::S_ENetwork, serial);
	});

	request->SetResponseHanler([=](const std::string & data) {
		Sender * from = LoginService::Instance().Find(client);
		if (!from) {
			LOG_ERR("[login]Interrupt verify because client is disconnected.");
			return;
		}

		Json::Value sina;
		Json::Reader reader;

		if (!reader.parse(data, sina) || !sina.isObject() || !sina["uid"].isString()) {
			LOG_ERR("[login]Verify failed : %s.", data.c_str());
			LoginService::Instance().FailedVerify(from, Proto::S_EBadParam, serial, true);
			return;
		}
		
		std::string account = sina["uid"].asString();
		LoginService::Instance().Link(account, from);
		CenterConnector::Instance().Verify(account, sid, code, serial);
	});
}